<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="90px"
    >
      <el-form-item label="帖子名称" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入帖子名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发帖人名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入发帖人名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['posts:posts:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['posts:posts:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['posts:posts:remove']"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="postsList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="帖子名称" align="center" prop="title" />
      <el-table-column label="发布者" align="center" prop="name" />
      <el-table-column label="帖子封面" align="center" prop="imageUrl">
        <template slot-scope="scope">
          <img
            :src="scope.row.imageUrl"
            alt="封面图片"
            style="width: 100px; height: 80px"
            v-if="scope.row.imageUrl"
          />
          <span v-else>无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="分类" align="center" prop="categoryName" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createdAt"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.createdAt, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="喜欢" align="center" prop="likes" />
      <el-table-column label="评论数量" align="center" prop="comments" />
      <el-table-column label="帖子状态" align="center" prop="status" >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.post_status"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="最后更新时间"
        align="center"
        prop="updatedAt"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.updatedAt, "{y}-{m}-{d} {h}:{i}:{s} ")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="帖子被浏览次数" align="center" prop="viewCount" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="320px"
      >
        <template slot-scope="scope">
          <div style="display: flex; justify-content: center; gap: 2px">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['posts:posts:edit']"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['posts:posts:remove']"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-discover"
              @click="handlecheck(scope.row)"
              v-hasPermi="['posts:posts:list']"
              >查看</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改帖子对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1000px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="帖子名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入帖子名称" />
        </el-form-item>
        <el-form-item label="封面图片" prop="imageUrl">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/common/minio/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="imageUrl"
              :src="imageUrl"
              class="avatar"
              @click="submitHandler"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="帖子分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="选择分类">
            <el-option
              v-for="dv in selectCategoryName"
              :key="dv.categoryId"
              :label="dv.name"
              :value="dv.categoryId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="内容">
          <editor v-model="form.content" :min-height="192" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看帖子对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="close"
      width="1000px"
      high="1000px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="内容">
          <editor v-model="form.content" read-only="true" :min-height="600" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>


<script>
import {
  listPosts,
  getPosts,
  delPosts,
  addPosts,
  updatePosts,
  getCategory
} from "@/api/posts/posts";

export default {
  name: "Posts",
  dicts: ["post_status"],
  data() {
    return {
      // 帖子分类
      selectCategoryName:[],
      // 图片地址
      imageUrl: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 帖子表格数据
      postsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      close: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        userId: null,
        name: null,
        content: null,
        createdAt: null,
        likes: null,
        comments: null,
        status: null,
        updatedAt: null,
        imageUrl: null,
        viewCount: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "帖子名称不能为空", trigger: "blur" },
        ],
        categoryId: [
          {
            required: true,
            message: "分类不为空",
            trigger: "blur",
          },
        ],
        content: [
          { required: true, message: "$comment不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getCategoryName()
  },
  methods: {
    // 获取文件分类
    getCategoryName() {
      getCategory().then(response => {
        // 获取后端的文件分类
        this.selectCategoryName = response.data
        console.log(this.selectCategoryName )
      })
    },
    /**图片格式 */
    handleAvatarSuccess(res, file) {
      console.log(res);

      this.imageUrl = URL.createObjectURL(file.raw);

      this.form.imageUrl = res.url;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    /**上传封面 */
    submitHandler() {
      if ($.validate.form()) {
        uploadFile();
      }
    },

    /** 查询帖子列表 */
    getList() {
      this.loading = true;
      listPosts(this.queryParams).then((response) => {
        this.postsList = response.rows;
        console.log( this.postsList)
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        postId: null,
        title: null,
        userId: null,
        name: null,
        content: null,
        createdAt: null,
        likes: null,
        comments: null,
        remark: null,
        status: null,
        updatedAt: null,
        imageUrl: null,
        viewCount: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.postId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加帖子";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const postId = row.postId || this.ids;
      getPosts(postId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改帖子";
      });
    },
    /** 查看内容按钮操作 */
    handlecheck(row) {
      this.reset();
      const postId = row.postId || this.ids;
      getPosts(postId).then((response) => {
        this.form.content = response.data.content;
        this.close = true;
        this.title = "查看帖子内容";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.postId != null) {
            updatePosts(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPosts(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
       }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const postIds = row.postId || this.ids;
      this.$modal
        .confirm('是否确认删除帖子编号为"' + postIds + '"的数据项？')
        .then(function () {
          return delPosts(postIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>
